﻿/*
 * @Autor: PK
 * @Date: 2021-03-31 13:34:14
 * @Description: .yml配置文件读取器
 */
using System;
using System.Collections.Generic;
using System.IO;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;


namespace ShkSimulation.core.util
{
    public class YamlReader {
        
        public static Dictionary<string, string> LoadYamlConfig(string yamlFilePath) {
            // Setup the input
            if (!File.Exists(yamlFilePath)) {
                throw new Exception(Environment.CurrentDirectory + "Yml文件不存在");
            }
            StringReader input = new StringReader(File.ReadAllText(yamlFilePath));
            //YamlStream yaml = new YamlStream();
            //yaml.Load(input);
            Dictionary<string, string> result = new Dictionary<string, string>();
            var deserializer = new DeserializerBuilder()
                .WithNamingConvention(CamelCaseNamingConvention.Instance)
                .Build();
            Dictionary<string, object> dictionary = deserializer.Deserialize<Dictionary<string, object>>(input);
            while (dictionary.Count > 0) {
                IEnumerable<string> keys = new List<string>(dictionary.Keys);
                foreach (var key in keys) {
                    object value = dictionary[key];
                    if (value is Dictionary<object, object> children) {
                        foreach (var each in children) {
                            dictionary.Add(key + "." + each.Key, each.Value);
                        }
                    } else {
                        result.Add(key, value.ToString());
                    }
                    dictionary.Remove(key);
                }
            }
            return result;
        }
        
    }
}
